package com.briup.sms_plus.server;


import com.briup.sms_plus.common.model.Request;
import com.briup.sms_plus.common.model.Response;
import com.briup.sms_plus.common.model.User;
import com.briup.sms_plus.common.util.InternetUtil;

import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器启动类
 */
public class ServerMain {
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8888);
        SmsController controller = new SmsController();
        // 一直接收来自客户端的连接
        boolean flag = true;
        while (flag) {
            // accept()方法能够等待来自于客户端的连接，如果没有客户端连接那么会一直处于阻塞状态
            Socket client = server.accept();
            System.out.println("接收来自于客户端的连接:" + client);
            // 创建多个线程处理任务
            Thread thread = new Thread(() -> {
                try {
                    handleTask(client, controller);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
        }
        server.close();
    }

    private static void handleTask(Socket client, SmsController controller) throws Exception {
        // 接收来自于客户端的数据，该数据依赖于客户端的发送，
        // 会一直等待客户端将数据发送，直到通知数据发送完毕
        Request<?> request = InternetUtil.receive(client, Request.class);
        // 响应对象
        Response<?> response = null;
        switch (request.getType()) {
            case "LOGIN":
                User data = (User) request.getData();
                User user = controller.login(data.getUsername(), data.getPassword());
                response = Response.builder()
                        .code(200).data(user)
                        .message("成功").build();
            case "QUERY_STUDENTS":

        }

        // 将结果响应给客户端
        InternetUtil.sendResponse(client, response);
    }
}
